package edu.ptu.shortlink.project.common.convention.result;


import edu.ptu.shortlink.project.common.convention.errorcode.BaseErrorCode;
import edu.ptu.shortlink.project.common.convention.exception.AbstractException;

import java.util.Optional;

/**
 * @BelongsProject: shortlink
 * @BelongsPackage: edu.ptu.shortlink.admin.common.convention
 * @Author: HYJ
 * @CreateTime: 2025-04-23  00:19
 * @Description: 统一响应结果工具类
 * @Version: 1.0
 */
public final class Results {

    /**
     * 构造成功响应
     *
     * @return 成功响应对象
     */
    public static Result<Void> success() {
        return new Result<Void>()
                .setCode(Result.SUCCESS_CODE);
    }

    /**
     * 构造成功响应
     *
     * @param data 响应数据
     * @param <T>  响应数据类型
     * @return 成功响应对象
     */
    public static <T> Result<T> success(T data) {
        return new Result<T>()
                .setCode(Result.SUCCESS_CODE)
                .setData(data);
    }

    /**
     * 构造失败响应
     *
     * @return 失败响应对象
     */
    public static Result<Void> failure() {
        return new Result<Void>()
                .setCode(BaseErrorCode.SERVICE_ERROR.code())
                .setMassage(BaseErrorCode.SERVICE_ERROR.message());
    }

    /**
     * {@link AbstractException}
     *
     * @param abstractException 异常对象
     * @return 失败响应对象
     */
    public static Result<Void> failure(AbstractException abstractException) {
        String errorCode = Optional.ofNullable(abstractException.getErrorCode())
                .orElse(BaseErrorCode.SERVICE_ERROR.code());

        String errorMessage = Optional.ofNullable(abstractException.getErrorMessage())
                .orElse(BaseErrorCode.SERVICE_ERROR.message());

        return new Result<Void>()
                .setCode(errorCode)
                .setMassage(errorMessage);
    }

    /**
     * 通过 errorCode 和 errorMessage 构造失败响应
     */
    public static Result<Void> failure(String errorCode, String errorMessage) {
        return new Result<Void>()
                .setCode(errorCode)
                .setMassage(errorMessage);
    }

}
